import { _decorator, Component, Vec3 } from 'cc';
import { Pathfinder } from './Pathfinder';
import { CharacterController } from '../controllers/CharacterController';

const { ccclass, property } = _decorator;

/**
 * 路径跟随器
 * 
 * 功能：
 * 1. 处理路径跟随逻辑
 * 2. 管理路径点更新
 * 3. 控制移动平滑度
 * 4. 处理路径重规划
 * 
 * 特点：
 * 1. 平滑的路径跟随
 * 2. 动态路径更新
 * 3. 避障功能
 * 4. 可配置的跟随参数
 */
@ccclass('PathFollower')
export class PathFollower extends Component {
    @property(Pathfinder)
    private pathfinder: Pathfinder | null = null;

    @property(CharacterController)
    private character: CharacterController | null = null;

    @property
    private pathUpdateRate: number = 0.5;

    @property
    private arrivalDistance: number = 0.1;

    private path: Vec3[] = [];
    private currentWaypoint: number = 0;
    private updateTimer: number = 0;
    private targetPosition: Vec3 | null = null;

    update(dt: number) {
        if (!this.targetPosition) return;

        this.updateTimer += dt;
        if (this.updateTimer >= this.pathUpdateRate) {
            this.updateTimer = 0;
            this.updatePath();
        }

        this.followPath();
    }

    public setTarget(target: Vec3) {
        this.targetPosition = target;
        this.updatePath();
    }

    private updatePath() {
        if (!this.pathfinder || !this.targetPosition) return;

        this.path = this.pathfinder.findPath(
            this.node.position,
            this.targetPosition
        );
        this.currentWaypoint = 0;
    }

    private followPath() {
        if (!this.character || this.path.length === 0) return;

        const currentWaypointPos = this.path[this.currentWaypoint];
        const direction = new Vec3();
        Vec3.subtract(direction, currentWaypointPos, this.node.position);

        if (direction.length() < this.arrivalDistance) {
            this.currentWaypoint++;
            if (this.currentWaypoint >= this.path.length) {
                this.path = [];
                this.character.move(Vec3.ZERO);
                return;
            }
        }

        direction.normalize();
        this.character.move(direction);
    }
} 